<template>
  <div class="resource-status-panel">
    <a-card title="资源状态管理" :bordered="false">
      <template #extra>
        <a-space>
          <a-button type="primary" @click="showCustomStatusModal = true">
            <template #icon>
              <IconifyIcon icon="ant-design:setting-outlined" />
            </template>
            自定义状态
          </a-button>
          <a-button @click="showSubscriptionModal = true">
            <template #icon>
              <IconifyIcon icon="ant-design:bell-outlined" />
            </template>
            状态订阅
          </a-button>
        </a-space>
      </template>

      <!-- 四重状态展示 -->
      <a-row :gutter="16">
        <!-- 生命周期状态 -->
        <a-col :span="6">
          <a-card size="small" title="生命周期状态">
            <div class="status-item">
              <a-tag :color="getStatusColor(resourceStatus.lifecycle)">
                {{ getStatusLabel(resourceStatus.lifecycle) }}
              </a-tag>
              <a-button
                type="link"
                size="small"
                @click="openStatusModal('lifecycle')"
              >
                修改
              </a-button>
            </div>
          </a-card>
        </a-col>

        <!-- 可用性状态 -->
        <a-col :span="6">
          <a-card size="small" title="可用性状态">
            <div class="status-item">
              <a-tag :color="getAvailabilityColor(resourceStatus.availability)">
                {{ getAvailabilityLabel(resourceStatus.availability) }}
              </a-tag>
              <a-button
                type="link"
                size="small"
                @click="showStatusModal('availability')"
              >
                修改
              </a-button>
            </div>
          </a-card>
        </a-col>

        <!-- 版本状态 -->
        <a-col :span="6">
          <a-card size="small" title="版本状态">
            <div class="status-item">
              <a-tag :color="getVersionColor(resourceStatus.version)">
                {{ getVersionLabel(resourceStatus.version) }}
              </a-tag>
              <a-button
                type="link"
                size="small"
                @click="showStatusModal('version')"
              >
                修改
              </a-button>
            </div>
          </a-card>
        </a-col>

        <!-- 自定义状态 -->
        <a-col :span="6">
          <a-card size="small" title="自定义状态">
            <div class="status-item">
              <a-tag
                v-if="resourceStatus.custom"
                :color="getCustomStatusColor(resourceStatus.custom.statusCode)"
              >
                {{ resourceStatus.custom.statusName }}
              </a-tag>
              <a-tag v-else color="default">未设置</a-tag>
              <a-button
                type="link"
                size="small"
                @click="showStatusModal('custom')"
              >
                {{ resourceStatus.custom ? '修改' : '设置' }}
              </a-button>
            </div>
          </a-card>
        </a-col>
      </a-row>

      <!-- 状态历史 -->
      <a-divider />
      <div class="status-history">
        <h4>状态变更历史</h4>
        <a-timeline>
          <a-timeline-item
            v-for="history in statusHistory"
            :key="history.id"
            :color="getHistoryColor(history.statusType)"
          >
            <div class="history-item">
              <div class="history-header">
                <span class="history-type">{{
                  getHistoryTypeLabel(history.statusType)
                }}</span>
                <span class="history-time">{{
                  formatTime(history.timestamp)
                }}</span>
              </div>
              <div class="history-content">
                <a-tag size="small">{{ history.oldStatus }}</a-tag>
                <IconifyIcon icon="ant-design:arrow-right-outlined" />
                <a-tag size="small" color="blue">{{ history.newStatus }}</a-tag>
              </div>
              <div v-if="history.reason" class="history-reason">
                原因：{{ history.reason }}
              </div>
              <div class="history-operator">操作者：{{ history.operator }}</div>
            </div>
          </a-timeline-item>
        </a-timeline>
      </div>
    </a-card>

    <!-- 状态修改模态框 -->
    <a-modal
      :open="showStatusModal"
      :title="getStatusModalTitle()"
      @ok="updateStatus"
      @cancel="showStatusModal = false"
    >
      <a-form layout="vertical">
        <a-form-item label="新状态">
          <a-select
            v-model:value="selectedStatus"
            placeholder="选择新状态"
            style="width: 100%"
          >
            <a-select-option
              v-for="option in statusOptions"
              :key="option.value"
              :value="option.value"
            >
              {{ option.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="变更原因">
          <a-textarea
            v-model:value="statusReason"
            placeholder="请输入状态变更原因"
            :rows="3"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 自定义状态管理模态框 -->
    <a-modal
      :open="showCustomStatusModal"
      title="自定义状态管理"
      width="1000px"
      @cancel="showCustomStatusModal = false"
    >
      <CustomStatusManager :resource-type="resourceType" />
    </a-modal>

    <!-- 状态订阅管理模态框 -->
    <a-modal
      :open="showSubscriptionModal"
      title="状态订阅管理"
      width="1000px"
      @cancel="showSubscriptionModal = false"
    >
      <StatusSubscriptionManager :resource-id="resourceId" />
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { IconifyIcon } from '@vben/icons';
import {
  ResourceLifecycleStatus,
  ResourceAvailabilityStatus,
  ResourceVersionStatus,
  type ResourceStatus,
  type StatusChangeHistory,
} from '#/api/resource-center/status-types';
import {
  updateResourceLifecycleStatus,
  updateResourceAvailabilityStatus,
  updateResourceVersionStatus,
  getResourceStatus,
  getResourceStatusHistory,
} from '#/api/resource-center/status-api';
import { updateResourceCustomStatus } from '#/api/resource-center/custom-status-api';
import CustomStatusManager from './CustomStatusManager.vue';
import StatusSubscriptionManager from './StatusSubscriptionManager.vue';

// Props
interface Props {
  resourceId: string;
  resourceType: string;
}

const props = defineProps<Props>();

// 响应式数据
const showStatusModal = ref(false);
const showCustomStatusModal = ref(false);
const showSubscriptionModal = ref(false);
const currentStatusType = ref<
  'lifecycle' | 'availability' | 'version' | 'custom'
>('lifecycle');
const selectedStatus = ref('');
const statusReason = ref('');

const resourceStatus = reactive<ResourceStatus>({
  lifecycle: ResourceLifecycleStatus.DRAFT,
  availability: ResourceAvailabilityStatus.UNAVAILABLE,
  version: ResourceVersionStatus.DRAFT,
  lastUpdated: new Date(),
});

const statusHistory = ref<StatusChangeHistory[]>([]);

// 计算属性
const statusOptions = computed(() => {
  switch (currentStatusType.value) {
    case 'lifecycle':
      return Object.values(ResourceLifecycleStatus).map((status) => ({
        label: getStatusLabel(status),
        value: status,
      }));
    case 'availability':
      return Object.values(ResourceAvailabilityStatus).map((status) => ({
        label: getAvailabilityLabel(status),
        value: status,
      }));
    case 'version':
      return Object.values(ResourceVersionStatus).map((status) => ({
        label: getVersionLabel(status),
        value: status,
      }));
    case 'custom':
      return [
        { label: '待审核', value: 'PENDING_REVIEW' },
        { label: '已审核', value: 'APPROVED' },
        { label: '已拒绝', value: 'REJECTED' },
        { label: '已激活', value: 'ACTIVE' },
        { label: '已暂停', value: 'SUSPENDED' },
        { label: '已归档', value: 'ARCHIVED' },
      ];
    default:
      return [];
  }
});

// 方法
const loadResourceStatus = async () => {
  try {
    const response = await getResourceStatus(props.resourceId);
    Object.assign(resourceStatus, response.data);
  } catch (error) {
    message.error('加载资源状态失败');
  }
};

const loadStatusHistory = async () => {
  try {
    const response = await getResourceStatusHistory(props.resourceId);
    statusHistory.value = response.data || [];
  } catch (error) {
    message.error('加载状态历史失败');
  }
};

const openStatusModal = (
  type: 'lifecycle' | 'availability' | 'version' | 'custom',
) => {
  currentStatusType.value = type;
  selectedStatus.value = '';
  statusReason.value = '';
  showStatusModal.value = true;
};

const updateStatus = async () => {
  if (!selectedStatus.value) {
    message.warning('请选择新状态');
    return;
  }

  try {
    switch (currentStatusType.value) {
      case 'lifecycle':
        await updateResourceLifecycleStatus(
          props.resourceId,
          selectedStatus.value as ResourceLifecycleStatus,
          statusReason.value,
        );
        break;
      case 'availability':
        await updateResourceAvailabilityStatus(
          props.resourceId,
          selectedStatus.value as ResourceAvailabilityStatus,
          statusReason.value,
        );
        break;
      case 'version':
        await updateResourceVersionStatus(
          props.resourceId,
          selectedStatus.value as ResourceVersionStatus,
          statusReason.value,
        );
        break;
      case 'custom':
        await updateResourceCustomStatus(
          props.resourceId,
          selectedStatus.value,
          statusReason.value,
        );
        break;
    }

    message.success('状态更新成功');
    showStatusModal.value = false;
    loadResourceStatus();
    loadStatusHistory();
  } catch (error) {
    message.error('状态更新失败');
  }
};

const getStatusModalTitle = () => {
  const titles = {
    lifecycle: '修改生命周期状态',
    availability: '修改可用性状态',
    version: '修改版本状态',
    custom: '修改自定义状态',
  };
  return titles[currentStatusType.value];
};

// 状态标签和颜色
const getStatusLabel = (status: ResourceLifecycleStatus) => {
  const labels = {
    [ResourceLifecycleStatus.DRAFT]: '草稿',
    [ResourceLifecycleStatus.ACTIVE]: '活跃',
    [ResourceLifecycleStatus.SUSPENDED]: '暂停',
    [ResourceLifecycleStatus.ARCHIVED]: '归档',
  };
  return labels[status] || status;
};

const getStatusColor = (status: ResourceLifecycleStatus) => {
  const colors = {
    [ResourceLifecycleStatus.DRAFT]: 'default',
    [ResourceLifecycleStatus.ACTIVE]: 'green',
    [ResourceLifecycleStatus.SUSPENDED]: 'orange',
    [ResourceLifecycleStatus.ARCHIVED]: 'red',
  };
  return colors[status] || 'default';
};

const getAvailabilityLabel = (status: ResourceAvailabilityStatus) => {
  const labels = {
    [ResourceAvailabilityStatus.AVAILABLE]: '可用',
    [ResourceAvailabilityStatus.RESERVED]: '已预订',
    [ResourceAvailabilityStatus.IN_USE]: '使用中',
    [ResourceAvailabilityStatus.UNAVAILABLE]: '不可用',
    [ResourceAvailabilityStatus.FAILED]: '故障',
  };
  return labels[status] || status;
};

const getAvailabilityColor = (status: ResourceAvailabilityStatus) => {
  const colors = {
    [ResourceAvailabilityStatus.AVAILABLE]: 'green',
    [ResourceAvailabilityStatus.RESERVED]: 'blue',
    [ResourceAvailabilityStatus.IN_USE]: 'orange',
    [ResourceAvailabilityStatus.UNAVAILABLE]: 'red',
    [ResourceAvailabilityStatus.FAILED]: 'red',
  };
  return colors[status] || 'default';
};

const getVersionLabel = (status: ResourceVersionStatus) => {
  const labels = {
    [ResourceVersionStatus.DRAFT]: '草稿',
    [ResourceVersionStatus.STAGED]: '已暂存',
    [ResourceVersionStatus.CANARY]: '金丝雀',
    [ResourceVersionStatus.ACTIVE]: '活跃',
    [ResourceVersionStatus.DEPRECATED]: '已废弃',
    [ResourceVersionStatus.ROLLED_BACK]: '已回滚',
  };
  return labels[status] || status;
};

const getVersionColor = (status: ResourceVersionStatus) => {
  const colors = {
    [ResourceVersionStatus.DRAFT]: 'default',
    [ResourceVersionStatus.STAGED]: 'blue',
    [ResourceVersionStatus.CANARY]: 'orange',
    [ResourceVersionStatus.ACTIVE]: 'green',
    [ResourceVersionStatus.DEPRECATED]: 'red',
    [ResourceVersionStatus.ROLLED_BACK]: 'red',
  };
  return colors[status] || 'default';
};

const getCustomStatusColor = (statusCode: string) => {
  const colors: Record<string, string> = {
    PENDING_REVIEW: 'orange',
    APPROVED: 'green',
    REJECTED: 'red',
    ACTIVE: 'blue',
    SUSPENDED: 'purple',
    ARCHIVED: 'default',
  };
  return colors[statusCode] || 'default';
};

const getHistoryTypeLabel = (type: string) => {
  const labels = {
    LIFECYCLE: '生命周期',
    AVAILABILITY: '可用性',
    VERSION: '版本',
    CUSTOM: '自定义',
  };
  return labels[type] || type;
};

const getHistoryColor = (type: string) => {
  const colors = {
    LIFECYCLE: 'blue',
    AVAILABILITY: 'green',
    VERSION: 'orange',
    CUSTOM: 'purple',
  };
  return colors[type] || 'default';
};

const formatTime = (timestamp: string | Date) => {
  return new Date(timestamp).toLocaleString('zh-CN');
};

// 生命周期
onMounted(() => {
  loadResourceStatus();
  loadStatusHistory();
});
</script>

<style lang="less" scoped>
.resource-status-panel {
  .status-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .status-history {
    h4 {
      margin-bottom: 16px;
    }

    .history-item {
      .history-header {
        display: flex;
        justify-content: space-between;
        margin-bottom: 8px;

        .history-type {
          font-weight: 500;
        }

        .history-time {
          color: #999;
          font-size: 12px;
        }
      }

      .history-content {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 4px;
      }

      .history-reason {
        color: #666;
        font-size: 12px;
        margin-bottom: 4px;
      }

      .history-operator {
        color: #999;
        font-size: 12px;
      }
    }
  }
}
</style>
